<template>
  <div class="message-center">
    <div class="section-header">
      <div class="left">
        <h3 class="section-title">消息通知</h3>
        <div class="message-count">共 {{ totalMessages }} 条消息</div>
      </div>
      <div class="right">
        <el-button-group>
          <el-button 
            :type="selectedType === 'all' ? 'primary' : 'default'"
            @click="selectedType = 'all'"
          >
            全部消息
          </el-button>
          <el-button 
            :type="selectedType === 'unread' ? 'primary' : 'default'"
            @click="selectedType = 'unread'"
          >
            未读消息
            <el-badge v-if="unreadCount > 0" :value="unreadCount" />
          </el-button>
        </el-button-group>
        
        <el-button type="primary" link @click="markAllAsRead">
          全部标为已读
        </el-button>
      </div>
    </div>
    
    <div class="message-list" v-loading="loading">
      <div 
        v-for="(group, date) in messageGroups" 
        :key="date"
        class="message-group"
      >
        <div class="group-date">{{ formatDate(date) }}</div>
        
        <div 
          v-for="message in group" 
          :key="message.id"
          class="message-item"
          :class="{ unread: !message.read }"
          @click="viewMessage(message)"
        >
          <div class="message-icon">
            <el-icon :class="getMessageIconClass(message.type)">
              <component :is="getMessageIcon(message.type)" />
            </el-icon>
          </div>
          
          <div class="message-content">
            <div class="message-title">{{ message.title }}</div>
            <div class="message-brief">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.time) }}</div>
          </div>
          
          <div class="message-action">
            <el-button 
              v-if="message.actionType === 'link'"
              type="primary" 
              link
              size="small"
              @click.stop="handleMessageAction(message)"
            >
              {{ message.actionText }}
            </el-button>
          </div>
        </div>
      </div>
      
      <el-empty 
        v-if="filteredMessages.length === 0" 
        :description="emptyText"
      />
      
      <div class="load-more" v-if="hasMore">
        <el-button link @click="loadMore">
          加载更多
        </el-button>
      </div>
    </div>
    
    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentMessage?.title"
      width="600px"
      destroy-on-close
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="detail-meta">
          <span class="time">{{ formatDateTime(currentMessage.time) }}</span>
          <span class="type">{{ getMessageTypeText(currentMessage.type) }}</span>
        </div>
        
        <div class="detail-content" v-html="currentMessage.content"></div>
        
        <div v-if="currentMessage.actionType" class="detail-action">
          <el-button 
            type="primary"
            @click="handleMessageAction(currentMessage)"
          >
            {{ currentMessage.actionText }}
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Bell,
  Message,
  Calendar,
  Document,
  Star
} from '@element-plus/icons-vue'

const router = useRouter()

// 状态变量
const loading = ref(false)
const selectedType = ref('all')
const messages = ref([
  {
    id: 1,
    type: 'interview',
    title: '面试邀请：前端开发工程师',
    content: '字节跳动向您发出面试邀请，请及时查看并确认。',
    time: '2023-05-15 14:30:00',
    read: false,
    actionType: 'link',
    actionText: '查看详情',
    actionData: { type: 'interview', id: 101 }
  },
  {
    id: 2,
    type: 'resume',
    title: '简历被查看通知',
    content: '您投递给腾讯科技的简历已被查看。',
    time: '2023-05-15 10:20:00',
    read: true,
    actionType: 'link',
    actionText: '查看职位',
    actionData: { type: 'job', id: 1001 }
  },
  {
    id: 3,
    type: 'system',
    title: '账号安全提醒',
    content: '您的账号已超过30天未修改密码，建议定期更换密码以保护账号安全。',
    time: '2023-05-14 16:45:00',
    read: false,
    actionType: 'link',
    actionText: '修改密码',
    actionData: { type: 'settings', tab: 'security' }
  },
  {
    id: 4,
    type: 'job',
    title: '职位更新提醒',
    content: '您收藏的职位"高级前端开发工程师"有新的更新。',
    time: '2023-05-14 09:15:00',
    read: true,
    actionType: 'link',
    actionText: '查看职位',
    actionData: { type: 'job', id: 1002 }
  },
  {
    id: 5,
    type: 'resume',
    title: '简历完善建议',
    content: '您的简历完整度较低，建议补充项目经验以提高简历竞争力。',
    time: '2023-05-13 11:30:00',
    read: true,
    actionType: 'link',
    actionText: '完善简历',
    actionData: { type: 'resume', id: 101 }
  }
])

// 消息详情对话框
const detailDialogVisible = ref(false)
const currentMessage = ref(null)

// 分页相关
const pageSize = 20
const hasMore = computed(() => filteredMessages.value.length < totalMessages.value)

// 计算未读消息数量
const unreadCount = computed(() => {
  return messages.value.filter(msg => !msg.read).length
})

// 计算总消息数量
const totalMessages = computed(() => {
  return messages.value.length
})

// 按日期分组的消息
const messageGroups = computed(() => {
  const groups = {}
  filteredMessages.value.forEach(msg => {
    const date = msg.time.split(' ')[0]
    if (!groups[date]) {
      groups[date] = []
    }
    groups[date].push(msg)
  })
  return groups
})

// 筛选后的消息列表
const filteredMessages = computed(() => {
  if (selectedType.value === 'unread') {
    return messages.value.filter(msg => !msg.read)
  }
  return messages.value
})

// 空状态文本
const emptyText = computed(() => {
  return selectedType.value === 'unread' ? '没有未读消息' : '暂无消息'
})

// 获取消息类型对应的图标
const getMessageIcon = (type) => {
  const iconMap = {
    'system': Bell,
    'message': Message,
    'interview': Calendar,
    'resume': Document,
    'job': Star
  }
  return iconMap[type] || Bell
}

// 获取消息图标的类名
const getMessageIconClass = (type) => {
  return `icon-${type}`
}

// 获取消息类型文本
const getMessageTypeText = (type) => {
  const textMap = {
    'system': '系统通知',
    'message': '私信消息',
    'interview': '面试通知',
    'resume': '简历通知',
    'job': '职位通知'
  }
  return textMap[type] || '系统通知'
}

// 格式化日期
const formatDate = (date) => {
  const today = new Date().toISOString().split('T')[0]
  const yesterday = new Date(Date.now() - 86400000).toISOString().split('T')[0]
  
  if (date === today) {
    return '今天'
  } else if (date === yesterday) {
    return '昨天'
  }
  return date
}

// 格式化时间
const formatTime = (datetime) => {
  return datetime.split(' ')[1].substring(0, 5)
}

// 格式化完整日期时间
const formatDateTime = (datetime) => {
  return datetime.replace(/:\d{2}$/, '')
}

// 查看消息详情
const viewMessage = (message) => {
  if (!message.read) {
    message.read = true
  }
  currentMessage.value = message
  detailDialogVisible.value = true
}

// 处理消息动作
const handleMessageAction = (message) => {
  detailDialogVisible.value = false
  
  const { type, id, tab } = message.actionData
  switch (type) {
    case 'interview':
      router.push(`/personal?tab=applications`)
      break
    case 'job':
      router.push(`/jobs/${id}`)
      break
    case 'resume':
      router.push(`/resumes/${id}/edit`)
      break
    case 'settings':
      router.push(`/personal?tab=account`)
      break
    default:
      break
  }
}

// 标记所有消息为已读
const markAllAsRead = async () => {
  try {
    // 实际应用中应该调用API
    // await messageApi.markAllAsRead()
    
    messages.value.forEach(msg => {
      msg.read = true
    })
    ElMessage.success('已全部标记为已读')
  } catch (error) {
    console.error('标记已读失败', error)
  }
}

// 加载更多消息
const loadMore = async () => {
  loading.value = true
  try {
    // 实际应用中应该调用API加载更多消息
    // const response = await messageApi.getMessages({
    //   page: Math.ceil(messages.value.length / pageSize) + 1,
    //   pageSize
    // })
    // messages.value.push(...response.data)
    
    // 模拟加载延迟
    setTimeout(() => {
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('加载更多消息失败', error)
    loading.value = false
  }
}

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true
  try {
    // 实际应用中应该调用API
    // const response = await messageApi.getMessages({
    //   page: 1,
    //   pageSize
    // })
    // messages.value = response.data
    
    // 模拟API延迟
    setTimeout(() => {
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取消息列表失败', error)
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchMessages()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.message-center {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-md);
    
    .left {
      .section-title {
        font-size: 1.2rem;
        font-weight: 600;
        color: var(--text-primary);
        margin: 0;
      }
      
      .message-count {
        color: var(--text-secondary);
        font-size: 0.9rem;
      }
    }
    
    .right {
      display: flex;
      align-items: center;
      gap: var(--spacing-md);
    }
  }
  
  .message-list {
    .message-group {
      margin-bottom: var(--spacing-xl);
      
      .group-date {
        font-size: 0.9rem;
        color: var(--text-secondary);
        margin-bottom: var(--spacing-md);
        padding-left: var(--spacing-sm);
        border-left: 2px solid var(--border-color);
      }
      
      .message-item {
        display: flex;
        align-items: flex-start;
        padding: var(--spacing-md);
        background-color: #fff;
        border-radius: var(--border-radius);
        margin-bottom: var(--spacing-sm);
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          background-color: var(--bg-secondary);
        }
        
        &.unread {
          background-color: var(--bg-secondary);
          
          .message-title {
            font-weight: 600;
            color: var(--text-primary);
          }
          
          .message-brief {
            color: var(--text-primary);
          }
        }
        
        .message-icon {
          margin-right: var(--spacing-md);
          color: var(--text-secondary);
          
          .el-icon {
            font-size: 1.2rem;
          }
        }
        
        .message-content {
          flex-grow: 1;
          margin-right: var(--spacing-md);
          
          .message-title {
            font-size: 1rem;
            color: var(--text-primary);
            margin-bottom: 4px;
          }
          
          .message-brief {
            font-size: 0.9rem;
            color: var(--text-secondary);
            margin-bottom: 4px;
          }
          
          .message-time {
            font-size: 0.9rem;
            color: var(--text-secondary);
          }
        }
      }
    }
  }
  
  .load-more {
    text-align: center;
    margin-top: var(--spacing-lg);
  }
}

.message-detail {
  .detail-meta {
    margin-bottom: var(--spacing-lg);
    color: var(--text-secondary);
    font-size: 0.9rem;
    
    .time {
      margin-right: var(--spacing-md);
    }
  }
  
  .detail-content {
    line-height: 1.6;
    color: var(--text-primary);
    margin-bottom: var(--spacing-lg);
  }
  
  .detail-action {
    text-align: center;
  }
}

// 响应式适配
@media (max-width: 768px) {
  .message-center {
    .section-header {
      flex-direction: column;
      align-items: flex-start;
      gap: var(--spacing-md);
      
      .right {
        width: 100%;
        justify-content: space-between;
      }
    }
    
    .message-list {
      .message-group {
        .message-item {
          padding: var(--spacing-sm);
          
          .message-icon {
            .el-icon {
              font-size: 1rem;
            }
          }
          
          .message-content {
            .message-title {
              font-size: 0.9rem;
            }
            
            .message-brief {
              font-size: 0.8rem;
            }
          }
        }
      }
    }
  }
}
</style> 